/**debugClient-websocket.js
 * 调试网络客户端 - WebSocket版本（支持USB调试）
 *
 * USB调试模式使用方式：
 * 1. 启动调试服务器: 在电脑上运行调试面板服务
 * 2. 设置端口转发: 执行 `adb reverse tcp:3000 tcp:3000`
 * 3. 在App中导入: import './utils/debugClient'
 * 4. 使用: global.$debug.info('Hello World')
 *
 * 局域网调试模式：
 * 1. 确保手机和电脑在同一WiFi网络
 * 2. 修改 serverUrl 为电脑的局域网IP
 * 3. 其他步骤同上
 *
 * 优势：
 * - 支持USB和WiFi两种连接方式
 * - 使用WebSocket实时通信
 * - 自动重连和降级机制
 * - 零依赖，纯JavaScript实现
 */

class DebugClient {
  constructor(config = {}) {
    // 默认USB调试配置（最常用）
    const defaultConfig = {
      serverUrl: 'http://localhost:3000', // USB调试模式
      enabled: typeof __DEV__ !== 'undefined' ? __DEV__ : true,
      useWebSocket: true,
      reconnectInterval: 3000,
      maxReconnectAttempts: 3,
      connectionTimeout: 5000,
      heartbeatInterval: 30000,
    }

    this.config = { ...defaultConfig, ...config }

    this._timers = new Map()
    this._logQueue = [] // 离线日志队列
    this._reconnectAttempts = 0
    this._isConnected = false
    this._ws = null
    this._heartbeatTimer = null
    this._connectionTimeout = null

    if (this.config.enabled) {
      this._initConnection()
      console.log('🚀 DebugClient initialized:', this.config.serverUrl)
    }
  }

  /**
   * 初始化连接（优先WebSocket，降级到HTTP）
   */
  _initConnection() {
    if (this.config.useWebSocket && typeof WebSocket !== 'undefined') {
      this._initWebSocket()
    } else {
      console.warn('WebSocket not available, using HTTP fallback')
      this._isConnected = true // HTTP模式直接标记为连接
    }
  }

  /**
   * 初始化WebSocket连接
   */
  _initWebSocket() {
    try {
      // 正确构建WebSocket URL，通常调试服务器的WebSocket端点在 /ws
      const wsUrl = this.config.serverUrl.replace(/^http/, 'ws') + '/ws'
      console.log('🔗 Connecting to WebSocket:', wsUrl)

      this._ws = new WebSocket(wsUrl)
      this._connectionTimeout = null

      // 设置连接超时
      this._connectionTimeout = setTimeout(() => {
        if (this._ws && this._ws.readyState === WebSocket.CONNECTING) {
          console.warn('⏰ WebSocket connection timeout, switching to HTTP mode')
          this._ws.close()
          this._isConnected = true // 降级到HTTP模式
          this._reconnectAttempts = this.config.maxReconnectAttempts // 停止重连
        }
      }, this.config.connectionTimeout)

      this._ws.onopen = () => {
        console.log('🔗 WebSocket connected to debug server')
        this._isConnected = true
        this._reconnectAttempts = 0

        // 清除连接超时
        if (this._connectionTimeout) {
          clearTimeout(this._connectionTimeout)
          this._connectionTimeout = null
        }

        // 启动心跳机制
        this._startHeartbeat()

        this._flushLogQueue() // 发送离线期间的日志
      }

      this._ws.onclose = (event) => {
        console.log('🔌 WebSocket connection closed, code:', event.code)
        this._isConnected = false

        // 停止心跳
        this._stopHeartbeat()

        // 清除连接超时
        if (this._connectionTimeout) {
          clearTimeout(this._connectionTimeout)
          this._connectionTimeout = null
        }

        // 只有不是主动关闭且不是正常关闭才重连
        if (event.code !== 1000 && event.code !== 1001) {
          console.log('🔄 Connection lost, attempting to reconnect...')
          this._handleReconnect()
        }
      }

      this._ws.onerror = (error) => {
        console.warn('❌ WebSocket error:', error.message || error)
        this._isConnected = false

        // 清除连接超时
        if (this._connectionTimeout) {
          clearTimeout(this._connectionTimeout)
          this._connectionTimeout = null
        }
      }

      this._ws.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data)
          if (data.type === 'connection') {
            console.log('✅ WebSocket connection confirmed:', data.message)
          } else {
            console.log('📨 Received from server:', data.type)
          }
        } catch (e) {
          console.log('📨 Received raw message:', event.data)
        }
      }
    } catch (error) {
      console.warn('WebSocket initialization failed, using HTTP fallback:', error.message)
      this._isConnected = true // 降级到HTTP模式
      this._reconnectAttempts = this.config.maxReconnectAttempts // 停止重连
    }
  }

  /**
   * 处理重连
   */
  _handleReconnect() {
    if (this._reconnectAttempts < this.config.maxReconnectAttempts) {
      this._reconnectAttempts++
      console.log(`🔄 Attempting to reconnect (${this._reconnectAttempts}/${this.config.maxReconnectAttempts})...`)

      // 增加递增延迟，避免频繁重连
      const delay = this.config.reconnectInterval + this._reconnectAttempts * 2000

      setTimeout(() => {
        if (this._reconnectAttempts <= this.config.maxReconnectAttempts && this.config.enabled) {
          this._initWebSocket()
        }
      }, delay)
    } else {
      console.warn('❌ Max reconnection attempts reached, switching to HTTP fallback mode')
      console.log('💡 HTTP mode: logs will be sent via regular HTTP requests')
      this._isConnected = true // 降级到HTTP模式
      this._ws = null // 清理WebSocket引用
    }
  }

  /**
   * 发送离线日志队列
   */
  _flushLogQueue() {
    if (this._logQueue.length > 0) {
      console.log(`📤 Flushing ${this._logQueue.length} queued logs`)
      this._logQueue.forEach((logData) => {
        this._sendViaWebSocket(logData)
      })
      this._logQueue = []
    }
  }

  /**
   * 通过WebSocket发送数据
   */
  _sendViaWebSocket(data) {
    if (this._ws && this._ws.readyState === WebSocket.OPEN) {
      this._ws.send(JSON.stringify(data))
      return true
    }
    return false
  }

  /**
   * 通过HTTP发送数据（降级方案）
   */
  async _sendViaHTTP(data) {
    try {
      const response = await fetch(`${this.config.serverUrl}/api/log`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      })

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`)
      }

      return true
    } catch (error) {
      console.warn('📡 HTTP send failed:', error.message)
      return false
    }
  }

  /**
   * 发送日志到远程调试面板
   */
  async _sendLog(level, messages) {
    if (!this.config.enabled) return

    const logData = {
      type: 'log',
      timestamp: Date.now().toString(),
      data: {
        id: Date.now() + Math.random(),
        timestamp: Date.now().toString(),
        level,
        message: messages.map((msg) => {
          if (typeof msg === 'object') {
            try {
              return JSON.stringify(msg, null, 2)
            } catch (e) {
              return String(msg)
            }
          }
          return String(msg)
        }),
        environment: this._getEnvironment(),
        userAgent: this._getUserAgent(),
      },
    }

    // 优先尝试WebSocket发送（仅当WebSocket真正连接时）
    if (this._ws && this._ws.readyState === WebSocket.OPEN && this._sendViaWebSocket(logData)) {
      return
    }

    // WebSocket不可用或失败，使用HTTP
    if (await this._sendViaHTTP(logData)) {
      return
    }

    // HTTP也失败了，加入离线队列
    this._logQueue.push(logData)
    if (this._logQueue.length > 100) {
      this._logQueue.shift() // 防止队列过长
    }

    console.warn('📡 Log failed to send, queued for retry. Queue size:', this._logQueue.length)
  }

  /**
   * 获取运行环境
   */
  _getEnvironment() {
    if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {
      return 'React Native'
    }
    if (typeof window !== 'undefined') {
      return 'Browser'
    }
    if (typeof process !== 'undefined' && process.versions && process.versions.node) {
      return 'Node.js'
    }
    return 'Unknown'
  }

  /**
   * 获取用户代理
   */
  _getUserAgent() {
    if (typeof navigator !== 'undefined') {
      return navigator.userAgent || 'Unknown'
    }
    return 'Unknown'
  }

  // ==================== 基础日志方法 ====================

  debug(...messages) {
    return this._sendLog('debug', messages)
  }

  info(...messages) {
    return this._sendLog('info', messages)
  }

  log(...messages) {
    return this._sendLog('log', messages)
  }

  warn(...messages) {
    return this._sendLog('warn', messages)
  }

  error(...messages) {
    return this._sendLog('error', messages)
  }

  // ==================== 业务场景方法 ====================

  userAction(action, details = {}) {
    return this.info(`👤 ${action}`, {
      type: 'user_action',
      action,
      details,
      timestamp: new Date().toISOString(),
    })
  }

  pageEvent(page, event, extra = {}) {
    return this.info(`📱 ${page} - ${event}`, {
      type: 'page_event',
      page,
      event,
      extra,
      timestamp: new Date().toISOString(),
    })
  }

  networkLog(method, url, requestData = null, responseData = null, duration = 0) {
    return this.info(`🌐 ${method.toUpperCase()} ${url}`, {
      type: 'network',
      method: method.toUpperCase(),
      url,
      requestData,
      responseData,
      duration,
      timestamp: new Date().toISOString(),
    })
  }

  errorLog(error, context = '') {
    return this.error(`❌ ${context}`, {
      type: 'error_log',
      message: error.message,
      stack: error.stack,
      context,
      timestamp: new Date().toISOString(),
    })
  }

  performanceLog(operation, duration, details = {}) {
    return this.info(`⚡ ${operation} (${duration}ms)`, {
      type: 'performance',
      operation,
      duration,
      details,
      timestamp: new Date().toISOString(),
    })
  }

  // ==================== 高级功能 ====================

  table(data, title = 'Table Data') {
    return this.info(`📊 ${title}`, {
      type: 'table',
      data,
      title,
      timestamp: new Date().toISOString(),
    })
  }

  time(label) {
    this._timers.set(label, Date.now())
    return this.debug(`⏱️ Timer '${label}' started`)
  }

  timeEnd(label) {
    const startTime = this._timers.get(label)

    if (startTime) {
      const duration = Date.now() - startTime
      this._timers.delete(label)
      return this.info(`⏱️ Timer '${label}': ${duration}ms`, {
        type: 'timer',
        label,
        duration,
        timestamp: new Date().toISOString(),
      })
    } else {
      return this.warn(`⏱️ Timer '${label}' does not exist`)
    }
  }

  async clear() {
    const clearData = {
      type: 'clear',
      timestamp: Date.now().toString(),
      data: { action: 'clear' },
    }

    // 优先尝试WebSocket，然后降级到HTTP
    let success = false
    if (this._ws && this._ws.readyState === WebSocket.OPEN) {
      success = this._sendViaWebSocket(clearData)
    }

    if (!success) {
      success = await this._sendViaHTTP(clearData)
    }

    if (success) {
      console.log('🧹 Remote logs cleared')
    } else {
      console.warn('📡 Clear logs failed')
    }
  }

  async testConnection() {
    const testData = {
      type: 'log',
      timestamp: Date.now().toString(),
      data: {
        id: Date.now(),
        timestamp: Date.now().toString(),
        level: 'info',
        message: ['🔗 Connection test'],
      },
    }

    // 优先尝试WebSocket，然后降级到HTTP
    let success = false
    if (this._ws && this._ws.readyState === WebSocket.OPEN) {
      success = this._sendViaWebSocket(testData)
    }

    if (!success) {
      success = await this._sendViaHTTP(testData)
    }

    if (success) {
      console.log('✅ Debug connection successful')
      return true
    } else {
      console.warn('❌ Debug connection failed')
      return false
    }
  }

  updateConfig(newConfig) {
    this.config = { ...this.config, ...newConfig }
    console.log('🔧 DebugClient config updated:', this.config)
  }

  getStatus() {
    const wsConnected = this._ws && this._ws.readyState === WebSocket.OPEN
    return {
      enabled: this.config.enabled,
      serverUrl: this.config.serverUrl,
      connected: this._isConnected,
      connectionType: wsConnected ? 'WebSocket' : 'HTTP',
      websocketReady: wsConnected,
      queuedLogs: this._logQueue.length,
      environment: this._getEnvironment(),
      reconnectAttempts: this._reconnectAttempts,
      maxReconnectAttempts: this.config.maxReconnectAttempts,
    }
  }

  /**
   * 启动心跳机制
   */
  _startHeartbeat() {
    this._stopHeartbeat() // 先清除之前的心跳

    this._heartbeatTimer = setInterval(() => {
      if (this._ws && this._ws.readyState === WebSocket.OPEN) {
        try {
          this._ws.send(JSON.stringify({ type: 'ping', timestamp: Date.now() }))
        } catch (error) {
          console.warn('心跳发送失败:', error.message)
          this._stopHeartbeat()
        }
      } else {
        this._stopHeartbeat()
      }
    }, this.config.heartbeatInterval)
  }

  /**
   * 停止心跳机制
   */
  _stopHeartbeat() {
    if (this._heartbeatTimer) {
      clearInterval(this._heartbeatTimer)
      this._heartbeatTimer = null
    }
  }

  /**
   * 断开连接
   */
  disconnect() {
    this._stopHeartbeat()
    if (this._ws) {
      this._ws.close()
      this._ws = null
    }
    this._isConnected = false
  }
}

// 创建全局实例
const $debug = new DebugClient()

// 挂载到全局
if (typeof global !== 'undefined') {
  global.$debug = $debug
} else if (typeof window !== 'undefined') {
  window.$debug = $debug
}

// 导出
if (typeof module !== 'undefined' && module.exports) {
  module.exports = $debug
}

// 初始化测试
if ($debug.config.enabled) {
  setTimeout(() => {
    $debug.info('🚀 DebugClient ready (WebSocket)', {
      environment: $debug._getEnvironment(),
      serverUrl: $debug.config.serverUrl,
      status: $debug.getStatus(),
    })
  }, 1000) // 等待WebSocket连接建立
}
